#!/usr/bin/env python3
"""
配置验证脚本 - 测试所有API连接
"""
import os
import sys
import asyncio
import httpx
from pathlib import Path
from dotenv import load_dotenv

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# 加载环境变量
load_dotenv()

async def test_deepseek_api():
    """测试DeepSeek API连接"""
    print("🔍 测试DeepSeek API...")
    
    api_key = os.getenv('DEEPSEEK_API_KEY')
    base_url = os.getenv('DEEPSEEK_BASE_URL')
    
    if not api_key or api_key.startswith('sk-dev'):
        print("❌ DeepSeek API Key未配置或为默认值")
        return False
    
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f"{base_url}/v1/chat/completions",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json"
                },
                json={
                    "model": "deepseek-chat",
                    "messages": [{"role": "user", "content": "Hello"}],
                    "max_tokens": 10
                },
                timeout=30.0
            )
            
            if response.status_code == 200:
                print("✅ DeepSeek API连接成功")
                return True
            else:
                print(f"❌ DeepSeek API响应错误: {response.status_code} - {response.text}")
                return False
                
    except Exception as e:
        print(f"❌ DeepSeek API连接失败: {str(e)}")
        return False

async def test_tongyi_api():
    """测试通义万相API连接"""
    print("🎨 测试通义万相API...")
    
    api_key = os.getenv('TONGYI_API_KEY')
    base_url = os.getenv('TONGYI_BASE_URL')
    
    if not api_key or api_key.startswith('dev-'):
        print("❌ 通义万相API Key未配置或为默认值")
        return False
    
    try:
        async with httpx.AsyncClient() as client:
            # 测试模型列表接口
            response = await client.get(
                f"{base_url}/api/v1/services/aigc/text2image/image-synthesis",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json"
                },
                timeout=30.0
            )
            
            # 通义万相API的认证检查
            if response.status_code in [200, 400]:  # 400可能是参数错误，但说明认证通过
                print("✅ 通义万相API连接成功")
                return True
            elif response.status_code == 401:
                print("❌ 通义万相API认证失败，请检查API Key")
                return False
            else:
                print(f"⚠️  通义万相API响应: {response.status_code}")
                return True  # 可能是参数问题，但连接正常
                
    except Exception as e:
        print(f"❌ 通义万相API连接失败: {str(e)}")
        return False

async def test_wechat_api():
    """测试微信公众号API连接"""
    print("📱 测试微信公众号API...")
    
    app_id = os.getenv('WECHAT_APP_ID')
    app_secret = os.getenv('WECHAT_APP_SECRET')
    
    if not app_id or app_id.startswith('dev_'):
        print("❌ 微信AppID未配置或为默认值")
        return False
    
    try:
        async with httpx.AsyncClient() as client:
            # 获取access_token
            wechat_base_url = os.getenv('WECHAT_BASE_URL', 'http://121.40.250.185')
            response = await client.get(
                f"{wechat_base_url}/cgi-bin/token",
                params={
                    "grant_type": "client_credential",
                    "appid": app_id,
                    "secret": app_secret
                },
                timeout=30.0
            )
            
            if response.status_code == 200:
                data = response.json()
                if "access_token" in data:
                    print("✅ 微信公众号API连接成功")
                    return True
                else:
                    print(f"❌ 微信API认证失败: {data.get('errmsg', '未知错误')}")
                    return False
            else:
                print(f"❌ 微信API请求失败: {response.status_code}")
                return False
                
    except Exception as e:
        print(f"❌ 微信API连接失败: {str(e)}")
        return False

def test_database():
    """测试数据库连接"""
    print("🗄️  测试数据库连接...")
    
    try:
        import pymysql
        
        host = os.getenv('DB_HOST')
        port = int(os.getenv('DB_PORT', 3306))
        user = os.getenv('DB_USER')
        password = os.getenv('DB_PASSWORD')
        database = os.getenv('DB_NAME')
        
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=database,
            charset='utf8mb4',
            connect_timeout=10
        )
        
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            cursor.fetchone()
        
        connection.close()
        print("✅ 数据库连接成功")
        return True
        
    except Exception as e:
        print(f"❌ 数据库连接失败: {str(e)}")
        return False

async def main():
    """主验证函数"""
    print("=" * 60)
    print("🔧 配置验证 - 微信公众号文章自动生成工具")
    print("=" * 60)
    
    results = []
    
    # 测试数据库
    results.append(test_database())
    
    # 测试API连接
    results.append(await test_deepseek_api())
    results.append(await test_tongyi_api())
    results.append(await test_wechat_api())
    
    print("\n" + "=" * 60)
    success_count = sum(results)
    total_count = len(results)
    
    if success_count == total_count:
        print("🎉 所有配置验证通过！可以正常启动应用了")
        print("运行命令: python run.py")
    else:
        print(f"⚠️  配置验证: {success_count}/{total_count} 通过")
        print("请检查失败的配置项")
    
    return success_count == total_count

if __name__ == "__main__":
    success = asyncio.run(main())
    sys.exit(0 if success else 1)